package com.example.teaching_server.controller;

import com.example.teaching_server.common.ApiResponse;
import com.example.teaching_server.dto.UserActivityDTO;
import com.example.teaching_server.dto.ActivityDTO;
import com.example.teaching_server.dto.ActivityListDTO;
import com.example.teaching_server.dto.DailyActivityStatusDTO;
import com.example.teaching_server.dto.CreateLaborActivityRequest;
import com.example.teaching_server.service.UserActivityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/user-activities")
@RequiredArgsConstructor
@Tag(name = "用户活动管理", description = "用户活动查询和管理接口")
public class UserActivityController {
    private final UserActivityService userActivityService;

    /**
     * 获取今日活动
     */
    @GetMapping("/today")
    @Operation(summary = "获取今日活动", description = "获取用户今日的活动列表")
    public ApiResponse<List<UserActivityDTO>> getTodayActivities(
            @Parameter(description = "用户ID")
            @RequestParam Long userId) {

        log.info("开始获取用户{}的今日活动", userId);

        try {
            List<UserActivityDTO> activities = userActivityService.getTodayActivities(userId);
            log.info("成功获取用户{}的{}个今日活动", userId, activities.size());
            return ApiResponse.success("今日活动获取成功", activities);
        } catch (Exception e) {
            log.error("获取今日活动失败: userId={}", userId, e);
            return ApiResponse.fail("获取今日活动失败: " + e.getMessage());
        }
    }

    /**
     * 按日期获取活动
     */
    @GetMapping("/by-date")
    @Operation(summary = "按日期获取活动", description = "获取用户指定日期的活动列表")
    public ApiResponse<List<UserActivityDTO>> getActivitiesByDate(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "查询日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {

        log.info("开始获取用户{}在{}的活动", userId, date);

        try {
            List<UserActivityDTO> activities = userActivityService.getActivitiesByDate(userId, date);
            log.info("成功获取用户{}在{}的{}个活动", userId, date, activities.size());
            return ApiResponse.success("指定日期活动获取成功", activities);
        } catch (Exception e) {
            log.error("获取指定日期活动失败: userId={}, date={}", userId, date, e);
            return ApiResponse.fail("获取指定日期活动失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有活动列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取活动列表", description = "获取所有活动列表，并标记用户是否已参与")
    public ApiResponse<List<ActivityListDTO>> getActivityList(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "搜索关键字") @RequestParam(required = false) String keyword,
            @Parameter(description = "基地ID") @RequestParam(required = false) Long baseId,
            @Parameter(description = "费用类型") @RequestParam(required = false) String fee) {

        log.info("开始获取活动列表: userId={}, keyword={}, baseId={}, fee={}", userId, keyword, baseId, fee);

        try {
            List<ActivityListDTO> activities = userActivityService.getAllActivities(userId, keyword, baseId, fee);
            log.info("成功获取{}个活动列表", activities.size());
            return ApiResponse.success("活动列表获取成功", activities);
        } catch (Exception e) {
            log.error("获取活动列表失败: userId={}", userId, e);
            return ApiResponse.fail("获取活动列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户已报名的活动列表
     */
    @GetMapping("/joined")
    @Operation(summary = "获取已报名活动", description = "获取用户已报名的活动列表")
    public ApiResponse<List<ActivityListDTO>> getJoinedActivities(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "搜索关键字") @RequestParam(required = false) String keyword,
            @Parameter(description = "基地ID") @RequestParam(required = false) Long baseId,
            @Parameter(description = "费用类型") @RequestParam(required = false) String fee) {

        log.info("开始获取用户{}的已报名活动: keyword={}, baseId={}, fee={}", userId, keyword, baseId, fee);

        try {
            List<ActivityListDTO> activities = userActivityService.getJoinedActivities(userId, keyword, baseId, fee);
            log.info("成功获取用户{}的{}个已报名活动", userId, activities.size());
            return ApiResponse.success("已参与活动列表获取成功", activities);
        } catch (Exception e) {
            log.error("获取已报名活动失败: userId={}", userId, e);
            return ApiResponse.fail("获取已参与活动列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户发布的活动列表
     */
    @GetMapping("/published")
    @Operation(summary = "获取发布的活动", description = "获取用户发布的活动列表")
    public ApiResponse<List<ActivityListDTO>> getPublishedActivities(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "搜索关键字") @RequestParam(required = false) String keyword,
            @Parameter(description = "基地ID") @RequestParam(required = false) Long baseId,
            @Parameter(description = "费用类型") @RequestParam(required = false) String fee) {

        log.info("开始获取用户{}发布的活动: keyword={}, baseId={}, fee={}", userId, keyword, baseId, fee);

        try {
            List<ActivityListDTO> activities = userActivityService.getPublishedActivities(userId, keyword, baseId, fee);
            log.info("成功获取用户{}发布的{}个活动", userId, activities.size());
            return ApiResponse.success("我发布的活动列表获取成功", activities);
        } catch (Exception e) {
            log.error("获取发布活动失败: userId={}", userId, e);
            return ApiResponse.fail("获取我发布的活动列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取每日活动状态
     */
    @GetMapping("/daily-status")
    @Operation(summary = "获取每日活动状态", description = "获取用户指定日期的活动状态")
    public ApiResponse<List<DailyActivityStatusDTO>> getDailyActivityStatus(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "查询日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {

        log.info("开始获取用户{}在{}的活动状态", userId, date);

        try {
            List<DailyActivityStatusDTO> statusList = userActivityService.getDailyActivityStatus(userId, date);
            log.info("成功获取用户{}在{}的{}条活动状态", userId, date, statusList.size());
            return ApiResponse.success("每日活动状态获取成功", statusList);
        } catch (Exception e) {
            log.error("获取每日活动状态失败: userId={}, date={}", userId, date, e);
            return ApiResponse.fail("获取每日活动状态失败: " + e.getMessage());
        }
    }

    /**
     * 报名活动
     */
    @PostMapping("/signup")
    @Operation(summary = "报名活动", description = "用户报名参加活动")
    public ApiResponse<String> signupActivity(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "活动ID") @RequestParam Long activityId) {

        log.info("开始用户{}报名活动{}", userId, activityId);

        try {
            boolean success = userActivityService.signupActivity(userId, activityId);
            if (success) {
                log.info("用户{}报名活动{}成功", userId, activityId);
                return ApiResponse.success("报名成功");
            } else {
                log.warn("用户{}报名活动{}失败，可能已报名或活动已满", userId, activityId);
                return ApiResponse.fail("报名失败，可能已报名或活动已满");
            }
        } catch (Exception e) {
            log.error("报名活动失败: userId={}, activityId={}", userId, activityId, e);
            return ApiResponse.fail("报名失败: " + e.getMessage());
        }
    }

    /**
     * 根据活动ID获取活动详情
     */
    @GetMapping("/details")
    @Operation(summary = "获取活动详情", description = "根据活动ID获取活动详细信息")
    public ApiResponse<ActivityDTO> getActivityById(
            @Parameter(description = "活动ID") @RequestParam Long activityId,
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId) {

        log.info("开始获取活动详情: activityId={}, userId={}", activityId, userId);

        try {
            ActivityDTO activity = userActivityService.getActivityById(activityId, userId);
            log.info("成功获取活动{}的详情", activityId);
            return ApiResponse.success("活动详情获取成功", activity);
        } catch (Exception e) {
            log.error("获取活动详情失败: activityId={}", activityId, e);
            return ApiResponse.fail("获取活动详情失败: " + e.getMessage());
        }
    }

    /**
     * RESTful方式获取活动详情
     */
    @GetMapping("/{activityId}")
    @Operation(summary = "获取活动详情(RESTful)", description = "根据活动ID获取活动详细信息")
    public ApiResponse<ActivityDTO> getActivity(
            @Parameter(description = "活动ID") @PathVariable Long activityId,
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId) {

        log.info("开始获取活动详情(RESTful): activityId={}, userId={}", activityId, userId);

        try {
            ActivityDTO activity = userActivityService.getActivityById(activityId, userId);
            log.info("成功获取活动{}的详情(RESTful)", activityId);
            return ApiResponse.success("活动详情获取成功", activity);
        } catch (Exception e) {
            log.error("获取活动详情失败(RESTful): activityId={}", activityId, e);
            return ApiResponse.fail("获取活动详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建新活动（劳动周专用）
     */
    @PostMapping("/create")
    @Operation(summary = "创建活动", description = "创建新的活动（劳动周专用）")
    public ApiResponse<ActivityDTO> createActivity(@RequestBody CreateLaborActivityRequest request) {
        log.info("开始创建活动");

        try {
            ActivityDTO activity = userActivityService.createActivity(request);
            log.info("活动创建成功");
            return ApiResponse.success("活动创建成功", activity);
        } catch (Exception e) {
            log.error("创建活动失败", e);
            return ApiResponse.fail("活动创建失败: " + e.getMessage());
        }
    }

    /**
     * 活动搜索接口
     */
    @GetMapping("/search")
    @Operation(summary = "搜索活动", description = "多条件搜索活动信息")
    public ApiResponse<List<ActivityListDTO>> searchActivities(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "搜索关键字") @RequestParam(required = false) String keyword,
            @Parameter(description = "基地ID") @RequestParam(required = false) Long baseId,
            @Parameter(description = "费用类型") @RequestParam(required = false) String fee,
            @Parameter(description = "活动状态：upcoming, ongoing, finished") @RequestParam(required = false) String status,
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        log.info("开始搜索活动: userId={}, keyword={}, baseId={}, fee={}, status={}, startDate={}, endDate={}",
                userId, keyword, baseId, fee, status, startDate, endDate);

        try {
            List<ActivityListDTO> activities = userActivityService.getAllActivities(userId, keyword, baseId, fee);

            // 根据状态筛选
            if (status != null && !status.trim().isEmpty()) {
                LocalDate today = LocalDate.now();
                activities = activities.stream()
                        .filter(activity -> {
                            if ("upcoming".equals(status)) {
                                return activity.getStartDate().isAfter(today);
                            } else if ("ongoing".equals(status)) {
                                return !activity.getStartDate().isAfter(today) &&
                                        !activity.getEndDate().isBefore(today);
                            } else if ("finished".equals(status)) {
                                return activity.getEndDate().isBefore(today);
                            }
                            return true;
                        })
                        .collect(Collectors.toList());
            }

            // 根据日期范围筛选
            if (startDate != null || endDate != null) {
                activities = activities.stream()
                        .filter(activity -> {
                            boolean match = true;
                            if (startDate != null) {
                                match = match && !activity.getEndDate().isBefore(startDate);
                            }
                            if (endDate != null) {
                                match = match && !activity.getStartDate().isAfter(endDate);
                            }
                            return match;
                        })
                        .collect(Collectors.toList());
            }

            log.info("成功搜索到{}个活动", activities.size());
            return ApiResponse.success("活动搜索成功", activities);
        } catch (Exception e) {
            log.error("搜索活动失败", e);
            return ApiResponse.fail("搜索活动失败: " + e.getMessage());
        }
    }
}
